package com.seeyon.apps.nygj.util;

import com.seeyon.ctp.common.SystemEnvironment;
import org.apache.commons.io.FileUtils;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.util.EntityUtils;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Map;


public class HttpKit {
    private static PoolingHttpClientConnectionManager cm;
    private static String EMPTY_STR = "";


    private static void init() {
        if (cm == null) {
            cm = new PoolingHttpClientConnectionManager();
            cm.setMaxTotal(50);// 整个连接池最大连接数
            cm.setDefaultMaxPerRoute(5);// 每路由最大连接数，默认值是2
        }
    }

    /**
     * 通过连接池获取HttpClient
     */
    private static CloseableHttpClient getHttpClient() {
        init();
        return HttpClients.custom().setConnectionManager(cm).build();
    }

    public static String post(String url, Map<String, Object> headers, String json) throws Exception {
        HttpPost httpPost = new HttpPost(url);
        if (!headers.isEmpty()) {
            for (Map.Entry<String, Object> param : headers.entrySet()) {
                httpPost.addHeader(param.getKey(), String.valueOf(param.getValue()));
            }
        }
        StringEntity entity = new StringEntity(json, "UTF-8");
        entity.setContentEncoding("utf-8");
        entity.setContentType("application/json");
        httpPost.setEntity(entity);
        return getResult(httpPost);
    }

    public static String postFile(String url, Map<String, Object> headers, Map<String, Object> body, File file) throws Exception {
        HttpPost httpPost = new HttpPost(url);

        if (!headers.isEmpty()) {
            for (Map.Entry<String, Object> param : headers.entrySet()) {
                httpPost.addHeader(param.getKey(), String.valueOf(param.getValue()));
            }
        }
        MultipartEntityBuilder builder = MultipartEntityBuilder.create();
        if (!body.isEmpty()) {
            ContentType contentType = ContentType.create("multipart/form-data", "UTF-8");
            builder.addBinaryBody("FILE", file, ContentType.DEFAULT_BINARY, URLEncoder.encode(file.getName(), "UTF-8"));
            builder.addTextBody("FileName", file.getName(), contentType);
            for (Map.Entry<String, Object> bodyMap : body.entrySet()) {
                builder.addTextBody(bodyMap.getKey(), String.valueOf(bodyMap.getValue()), contentType);
            }
        }
        builder.setCharset(StandardCharsets.UTF_8);
        builder.setMode(HttpMultipartMode.RFC6532);
        HttpEntity httpEntity = builder.build();
        httpPost.setEntity(httpEntity);
        return getResult(httpPost);
    }

    /**
     * 处理Http请求
     *
     * @param request
     * @return
     */
    private static String getResult(HttpRequestBase request) throws Exception {
        CloseableHttpClient httpClient = getHttpClient();
        CloseableHttpResponse response = httpClient.execute(request);
        HttpEntity entity = response.getEntity();
        if (entity != null) {
            String result = EntityUtils.toString(entity, "UTF-8");//主数据接口 乱码 加响应编码
            response.close();
            return result;
        }
        return EMPTY_STR;
    }

    public static String get(String url, Map<String, Object> headerMap) throws Exception {
        HttpGet httpGet = new HttpGet(url);
        if (!headerMap.isEmpty()) {
            // 遍历headers参数的每个键值对
            for (Map.Entry<String, Object> param : headerMap.entrySet()) {
                // 向httpGet对象添加Header参数，键为param的键，值为param的值的字符串形式
                httpGet.addHeader(param.getKey(), String.valueOf(param.getValue()));
            }
        }
        return getResult(httpGet);
    }

    public static File getFile(String url,String fileName) throws Exception {
        HttpGet httpGet = new HttpGet(url);
        return getFileResult(httpGet,fileName);
    }

    private static File getFileResult(HttpRequestBase request,String fileName) throws IOException {
        CloseableHttpResponse response = null;
        File file = null;
        try {
            CloseableHttpClient httpClient = getHttpClient();
            response = httpClient.execute(request);
            HttpEntity entity = response.getEntity();
            InputStream inputStream = entity.getContent();
            if (entity != null) {
                String systemUrl = SystemEnvironment.getBaseFolder().replaceAll("\\\\", "/");
                String pathUrl = systemUrl+"/upload/customFile/";
                File filePath = new File(pathUrl);
                if(!filePath.exists()) {
                    createFolder(pathUrl);
                }
                String fileUrl = pathUrl+fileName;
                file = new File(fileUrl);
                FileUtils.copyInputStreamToFile(inputStream, file);
                return file;
            }
        } catch (Exception e) {
            return file;
        }finally {
            if(response != null) {
                response.close();
            }
        }
        return file;

    }
    private static File createFolder(String path) {
        File ret = null;
        File file = new File(path);
        if (!file.exists()) {
            if (file.mkdirs()) {
                ret = file;
            }
        } else {
            ret = file;
        }
        return ret;
    }


}
